package com.english.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.english.entity.FreeLessonTimeSlot;
import com.english.mapper.FreeLessonTimeSlotMapper;
import com.english.service.FreeLessonTimeSlotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Date;

@Service
public class FreeLessonTimeSlotServiceImpl implements FreeLessonTimeSlotService {

    @Autowired
    private FreeLessonTimeSlotMapper timeSlotMapper;

    @Override
    public void createTimeSlot(FreeLessonTimeSlot slot) {
        slot.setStatus(1);
        slot.setIsOccupied(0);
        slot.setCurrentStudents(0);
        timeSlotMapper.insert(slot);
    }

    @Override
    public List<FreeLessonTimeSlot> getAvailableSlots(LocalDate date) {
        QueryWrapper<FreeLessonTimeSlot> qw = new QueryWrapper<>();
        qw.eq("date", date).eq("status", 1).eq("is_occupied", 0);
        return timeSlotMapper.selectList(qw);
    }

    @Override
    public void deleteTimeSlot(Long id) {
        timeSlotMapper.deleteById(id);
    }
    
    @Override
    public FreeLessonTimeSlot getTimeSlotById(Long id) {
        return timeSlotMapper.selectById(id);
    }
    
    @Override
    public boolean updateTimeSlot(FreeLessonTimeSlot timeSlot) {
        // 设置更新时间
        timeSlot.setUpdateTime(new Date());
        
        // 验证时段是否存在
        FreeLessonTimeSlot existingSlot = timeSlotMapper.selectById(timeSlot.getId());
        if (existingSlot == null) {
            return false;
        }
        
        // 如果时段已被占用且当前学生数大于0，不允许修改
        if (existingSlot.getIsOccupied() == 1 && existingSlot.getCurrentStudents() > 0) {
            throw new RuntimeException("该时段已有学生预约，无法修改");
        }
        
        // 更新时段信息
        int result = timeSlotMapper.updateById(timeSlot);
        return result > 0;
    }
} 
